﻿using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Volo.Abp.Security.Claims;

namespace Demo.Abp.Extension;

public class CurrentUserMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ICurrentPrincipalAccessor _currentPrincipalAccessor;

    public CurrentUserMiddleware(RequestDelegate next,ICurrentPrincipalAccessor currentPrincipalAccessor)
    {
        _next = next;
        _currentPrincipalAccessor = currentPrincipalAccessor;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        string uid = context.Request.Headers["UserId"];
        if (!uid.IsNullOrEmpty())
        {
            //如果获取到用户ID，则作为当前用户ID
            var newPrincipal = new ClaimsPrincipal(
                new ClaimsIdentity(
                    new Claim[]
                    {
                        new Claim(AbpClaimTypes.UserId, uid),
                    }
                )
            );

            using (_currentPrincipalAccessor.Change(newPrincipal))
            {
                await _next(context);
            }
        }
        else
        {
            //如果未获取到用户ID则忽略此项继续执行后面的逻辑
            await _next(context);
        }
    }
}